public class HashBuck {
    //哈希桶
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] arr;
    public int usedSize;
    public double loadFactorCount = 0.75;

    public HashBuck() {
        arr = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % arr.length;
        Node cur = arr[index];
        //1.遍历当前链表，是否存在当前值
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //2.说明没有当前值，此时进行头插
        Node node = new Node(key, val);
        node.next = arr[index];
        arr[index] = node;
        usedSize++;
        //3.超过负载因子0.75进行扩容
        if (loadFactorCount() >= loadFactorCount) {
            //对数组进行扩容
            resize();
        }

    }

    private void resize() {
        Node[] arr1 = new Node[arr.length * 2];
        for (int i = 0; i < arr.length; i++) {
            Node cur = arr[i];
            //开始遍历链表
            while (cur != null) {
                int index1 = cur.key % arr1.length;
                //把数据存放在新数组arr1位置
                Node cur1 = cur.next;
                cur.next = arr1[index1];
                arr1[index1] = cur;
                cur = cur1;
            }
        }
        arr = arr1;
    }

    private double loadFactorCount() {
        return usedSize * 1.0 / arr.length;
    }

    public int get(int key) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
